package com.example.config;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService1 {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisService1(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void exampleOperations() {
        // 设置值
        stringRedisTemplate.opsForValue().set("key", "value");

        // 获取值
        String value = stringRedisTemplate.opsForValue().get("key");
        System.out.println("Value: " + value);

        // 设置过期时间
        stringRedisTemplate.expire("key", 60, java.util.concurrent.TimeUnit.SECONDS);

        // 执行事务
        stringRedisTemplate.execute((RedisCallback<Object>) connection -> {
            connection.multi();
            connection.set("key1".getBytes(), "value1".getBytes());
            connection.set("key2".getBytes(), "value2".getBytes());
            return connection.exec();
        });
    }
}
